from django.contrib import auth
from django.contrib.auth import login
from django.shortcuts import render, HttpResponse
from django.views import View
from django.http import JsonResponse
from django.db import DatabaseError
from django_redis import get_redis_connection
from django.forms import model_to_dict
import re

from Users.models import User

# 用户登录
class UserLoginView(View):
    """
    用户登录
    """
    def get(self, request):
        return HttpResponse("用户登录")

    def post(self, request):
        # 接收参数：表单参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        uuid = request.POST.get('uuid')
        image_code = request.POST.get('image_code')
        print("%s, %s, %s, %s" % (username, password, uuid, image_code))

        #  判断参数是否正确
        if not all([username, password, uuid, image_code]):
            return HttpResponse({'msg': '缺少必传参数'})  # 缺少必传的参数

        # 验证图形验证码
        redis_conn = get_redis_connection('verify_code')
        image_code_server = redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            return JsonResponse({'code': 4002, 'msg': '图形验证码已失效'})
        redis_conn.delete('img_%s' % uuid)
        # 对比图形验证码,
        image_code_server = image_code_server.decode()  # 将byte转成字符串全部转成小写字母，再比较
        if image_code_server.lower() != image_code:
            return JsonResponse({'code': 4001, 'msg': '输入的图形验证码有误'})

        # 查数据库
        user = auth.authenticate(username=username, password=password)
        if user is not None and user.is_active:
            # 状态保持
            auth.login(request, user)
            # 记住登录；状态保持的周期为两周
            request.session.set_expiry(None)

            response = JsonResponse({'code': 200, 'msg': "登录成功"})
            # 实现在首页展示用户信息，将用户名缓存到cookie中,2周
            response.set_cookie('username', user.username, max_age=3600*24*15)
            return response

        else:
            # 登陆失败
            return JsonResponse({'code': 0, 'msg': '密码错误'})



# 手机号是否重复
class mobileCountView(View):
    """
    判断手机号码是否重复注册
    :param: mobile: 用户名
    :return: JSON
    """
    def get(self, request, mobile):
        # 使用username查询对应记录的条数(filter返回的是满足条件的结果集)
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})

# 用户名是否重复
class UsernameCountView(View):
    """
    判断用户名是否重复注册
    :param: username: 用户名
    :return: JSON
    """
    def get(self, request, username):
        # 使用username查询对应记录的条数(filter返回的是满足条件的结果集)
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})


# 用户注册逻辑
class UserRegister(View):

    def get(self, request):
        return HttpResponse("接到get请求")

    def post(self, request):
        # 接收参数：表单参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        check_password = request.POST.get('check_password')
        mobile = request.POST.get('mobile')
        uuid = request.POST.get('uuid')
        image_code = request.POST.get('image_code')
        print("%s, %s, %s, %s %s %s" % (username, mobile, password, check_password, uuid, image_code))

        #  判断参数是否正确
        if not all([username, password, check_password, mobile,  uuid, image_code]):
            return HttpResponse({'msg': '缺少必传参数'})  # 缺少必传的参数
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({'msg': '请输入5-20个字符的用户名'})
        if not re.match(r'^[0-9A-Za-z]{6,20}$', password):
            return JsonResponse({'msg': '请输入8-20位密码'})
        if password != check_password:
            return JsonResponse({'msg': '两次输入的密码不一致'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'msg': '请输入正确的手机号码'})

        # 验证图形验证码
        redis_conn = get_redis_connection('verify_code')
        image_code_server = redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            return JsonResponse({'code': 404, 'msg': '图形验证码已失效'})
        redis_conn.delete('img_%s' % uuid)
        # 对比图形验证码,
        image_code_server = image_code_server.decode()  # 将byte转成字符串全部转成小写字母，再比较
        if image_code_server.lower() != image_code:
            return JsonResponse({'code': 4001, 'msg': '输入的图形验证码有误'})

        # 写入数据库
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except DatabaseError:
            return JsonResponse({'code': 0, 'msg': "注册失败"})

        # 状态保持
        login(request, user)

        # 响应结果
        return JsonResponse({'code': 200, 'msg': "OK"})
